package com.kanshu.ksgb.fastread.doudou.module.book.view;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dl7.recycler.adapter.BaseQuickAdapter;
import com.dl7.recycler.adapter.BaseViewHolder;
import com.dl7.recycler.divider.GridDivider;
import com.dl7.recycler.helper.RecyclerViewHelper;
import com.google.gson.reflect.TypeToken;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.util.DiskLruCacheUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.taglayout.TagLayout;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.SelectedBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.retrofit.SelectedRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

import static com.kanshu.ksgb.fastread.doudou.base.baseui.SwipeBackActivity.ACTION_DESTORY;

/**
 * Created by wcy on 18/5/27.
 */

public class AdSearchHotAndHistoryLayout extends LinearLayout {
    @BindView(R.id.ad_container)
    FrameLayout mAdContainer;
    @BindView(R.id.top_divider)
    View mTopDivider;
    @BindView(R.id.hot_search)
    RecyclerView mHotSearch;
    @BindView(R.id.bottom_divider)
    View mBottomDivider;
    @BindView(R.id.divider)
    View mDivider;
    @BindView(R.id.tag_container)
    TagLayout mTagContainer;
    @BindView(R.id.search_label)
    TextView mSearchLabel;
    @BindView(R.id.search_history_del)
    ImageView mSearchHistoryDel;
    private String mHistoryKey;
    private List<String> mHistoryList = new ArrayList<>();
    IItemClickCallback mCallback;
    public Subject<Integer> lifeCyclerSubject = PublishSubject.create();
    IHotSearchKeyCallback mIHotSearchKeyCallback;

    public void setCallback(IItemClickCallback callback) {
        mCallback = callback;
    }

    public void setHotSearchCallback(IHotSearchKeyCallback callback) {
        mIHotSearchKeyCallback = callback;
    }

    public AdSearchHotAndHistoryLayout(Context context) {
        super(context);
        init();
    }

    public AdSearchHotAndHistoryLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AdSearchHotAndHistoryLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOrientation(VERTICAL);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_search_hot_and_history, this);
        ButterKnife.bind(view);
        mHotSearch.addItemDecoration(new GridDivider(1, 1, 2));
        mHistoryKey = UserUtils.getUserId() + "search_history";
        mHotSearch.setHasFixedSize(true);
        mHotSearch.setNestedScrollingEnabled(false);
        AdUtils.fetchAdUtil((Activity) getContext(), mAdContainer, null, ADConfigBean.POSITION_SEARCH_TOP, AdStyleBean.BANNER_STYLE, 0, null);
    }

    /**
     * 刷新
     */
    public void refresh() {
        BookCityPresenter presenter = new BookCityPresenter(lifeCyclerSubject);
        SelectedRequestParams params = new SelectedRequestParams();
        params.type_name = Constants.BookCityModuleType.TYPE_SEARCH_HOT;
        params.page = 1;
        params.num = 6;
        presenter.getHotSearch(params, new INetCommCallback<SelectedBean>() {
            @Override
            public void onResponse(SelectedBean selectedBean) {
                if (selectedBean != null && !Utils.isEmptyList(selectedBean.list)) {
                    if (selectedBean.list.size() > 6) {
                        selectedBean.list = selectedBean.list.subList(0, 6);
                    }
                    mIHotSearchKeyCallback.onHotSearchKey(selectedBean.list.get(0).title);
                    DisplayUtils.visible(mTopDivider, mDivider, mHotSearch);
                    HotAdapter adapter = new HotAdapter(getContext(), selectedBean.list);
                    RecyclerViewHelper.initRecyclerViewG(getContext(), mHotSearch, adapter, 2);
                    adapter.setOnItemClickListener((view, position) -> {
                        if (mCallback != null) {
                            mCallback.onItemClcik(selectedBean.list.get(position).title, null);
                        }
                    });
                }
                processHistoryShow();
            }

            @Override
            public void onError(int code, String errDesc) {
                DisplayUtils.gone(mTopDivider, mBottomDivider, mDivider, mHotSearch);
                processHistoryShow();
            }
        });
    }

    private void processHistoryShow() {
        mTagContainer.setHorizontalInterval(DisplayUtils.dip2px(getContext(), 14));
        mTagContainer.setVerticalInterval(DisplayUtils.dip2px(getContext(), 12));
        Type type = new TypeToken<ArrayList<String>>() {
        }.getType();
        List<String> historyList = DiskLruCacheUtils.get(mHistoryKey, type);
        if (Utils.isEmptyList(historyList)) {
            DisplayUtils.gone(mTagContainer, mSearchLabel, mDivider, mSearchHistoryDel);
        } else {
            DisplayUtils.visible(mTagContainer, mSearchLabel, mDivider, mSearchHistoryDel);
            mTagContainer.setTags(historyList);
            mHistoryList = historyList;
        }
        mTagContainer.setTagClickListener((position, text, tagMode) -> {
            if (mCallback != null) {
                mCallback.onItemClcik(text, null);
            }
        });
    }


    /**
     * 添加到搜索历史记录
     *
     * @param s
     */
    public void handleSearchHistory(String s) {
        if (mHistoryList == null) {
            mHistoryList = new ArrayList<>();
        }
        for (int i = mHistoryList.size() - 1; i >= 0; i--) {
            if (s.equals(mHistoryList.get(i))) {
                mHistoryList.remove(i);
                break;
            }
        }
        mHistoryList.add(0, s);
        if (mHistoryList.size() > 5) {
            mHistoryList = mHistoryList.subList(0, 5);
        }
        DiskLruCacheUtils.put(mHistoryKey, mHistoryList);
        DisplayUtils.visible(mTagContainer, mSearchLabel, mDivider, mSearchHistoryDel);
        mTagContainer.setTags(mHistoryList);
    }

    @OnClick(R.id.search_history_del)
    public void onViewClicked() {
        mHistoryList.clear();
        DiskLruCacheUtils.put(mHistoryKey, mHistoryList);
        mTagContainer.setTags(mHistoryList);
        DisplayUtils.gone(mTagContainer, mSearchLabel, mDivider, mSearchHistoryDel);
    }

    class HotAdapter extends BaseQuickAdapter<BookInfo> {

        public HotAdapter(Context context, List<BookInfo> data) {
            super(context, data);
        }

        @Override
        protected int attachLayoutRes() {
            return R.layout.item_search_hot_item_layout;
        }

        @Override
        protected void convert(BaseViewHolder holder, BookInfo item, int position) {
            holder.setText(R.id.info, item.title);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        AdUtils.destroyAd(mAdContainer);
        lifeCyclerSubject.onNext(ACTION_DESTORY);
    }
}
